#include "httpclient.h"

HttpClient::HttpClient(QString host, int port)
{
    m_host = host;
    m_http = new QHttp(host, port);
    m_cookies = "";
    m_data = "";
    response = 0;
    responseMsg = "";
    //TODO: connect signals
    connect(m_http, SIGNAL(done(bool)), this, SLOT(done(bool)));
    connect(m_http, SIGNAL(responseHeaderReceived(QHttpResponseHeader)),
            this, SLOT(responseHeaderReceived(QHttpResponseHeader)));
}

HttpClient::~HttpClient()
{
    m_http->abort();
    m_http->close();
    delete m_http;
}

void HttpClient::doRequest(QString url)
{
    QHttpRequestHeader req("GET", url);
    req.addValue("Host", m_host);
    req.addValue("Cookie", m_cookies);
    req.addValue("Cookie2", "$Version=1");
    req.addValue("Referer", "http://"+m_host+"/login?pda=index");
    m_data = "";
    m_http->request(req);
    qDebug("GET %s", url.toAscii().data());
}

void HttpClient::doRequest(QString url, QByteArray content)
{
    QHttpRequestHeader req("POST", url);
    req.addValue("Host", m_host);
    req.addValue("Cookie", m_cookies);
    req.addValue("Cookie2", "$Version=1");
    req.addValue("Referer", "http://"+m_host+"/login?pda=index");
    req.setContentType("application/x-www-form-urlencoded");
    req.setContentLength(content.length());
    m_data = "";
    m_http->request(req, content);
    qDebug("POST %s", url.toAscii().data());
}

void HttpClient::setConnectionInfo(QString host, int port)
{
    m_http->setHost(host, port);
}

void HttpClient::setProxyInfo(bool useProxy, QString proxyHost, int proxyPort,
                              bool useProxyAuth, QString proxyUser, QString proxyPass)
{
    if (useProxy && useProxyAuth)
        m_http->setProxy(proxyHost, proxyPort, proxyUser, proxyPass);
    else if (useProxy && !useProxyAuth)
        m_http->setProxy(proxyHost, proxyPort, "", "");
    else
        m_http->setProxy("", 0, "", "");
}

void HttpClient::responseHeaderReceived(const QHttpResponseHeader &resp)
{
    response = resp.statusCode();
    responseMsg = resp.reasonPhrase();
    qDebug("Response: %d %s", response, responseMsg.toAscii().data());
    QPair<QString, QString> pair;
    foreach (pair, resp.values())
    {
        if (pair.first.toAscii() == "Set-Cookie")
        {
            int pos = pair.second.indexOf(";");
            QString cur = pair.second.toAscii();
            cur.truncate(pos);
            m_cookies.append(cur).append("; ");
        }
    }
}

void HttpClient::done(bool error)
{
    m_data = m_http->readAll();
    if (!error)
    {
        emit requestDone(&m_data);
    }
    else
    {
        emit requestError(m_http->errorString());
        qDebug("Request error: %s", m_http->errorString().toAscii().data());
    }
}
